const renderer = (vdom, container) => {
  container.innerHTML = ''
  container.appendChild(createElement(vdom))
}

export default renderer

const createElement = vdom => {
  const [type, props, ...children] = vdom
  if (typeof type === 'function') {
    if (type.prototype && 'function' === typeof type.prototype.render) {
      const Component = type
      const component = new Component({ ...props, children })
      if ('function' === typeof component.beforeRender) {
        component.beforeRender()
      }
      return createElement(component.render())
    }
    const component = type
    return createElement(component({ ...props, children }))
  }

  const element = document.createElement(type)

  for (let key in props) {
    if (key in element) {
      element[key] = props[key]
    } else {
      element.setAttribute(key, props[key])
    }
  }

  children.forEach(child => {
    const childNode = createChild(child)
    if (childNode) {
      element.appendChild(childNode)
    }
  })

  return element

}

const createChild = child => {
  if (Array.isArray(child)) {
    return createElement(child)
  } else if (child != null && typeof child != 'boolean') {
    return document.createTextNode(child)
  }
}
